// 回调处理相关功能实现

use thiserror::Error;
use std::any::Any;
use std::sync::Arc;
use std::sync::Mutex;
use std::collections::HashMap;

// 定义回调错误类型
#[derive(Error, Debug)]
pub enum CallbackError {
    #[error("Callback registration failed")]
    RegistrationFailed,
    
    #[error("Callback not found")]
    CallbackNotFound,
    
    #[error("Callback execution failed")]
    ExecutionFailed,
    
    #[error("Invalid callback ID")]
    InvalidCallbackId,
}

// 定义回调ID类型
pub type CallbackId = u64;

// 定义回调处理特性
pub trait CallbackHandler: Send + Sync + 'static {
    fn call(&self, args: Box<dyn Any>) -> Box<dyn Any>;
}

// 实现函数指针作为回调处理器
impl CallbackHandler for fn(Box<dyn Any>) -> Box<dyn Any> {
    fn call(&self, args: Box<dyn Any>) -> Box<dyn Any> {
        (*self)(args)
    }
}

// 回调注册表
pub struct CallbackRegistry {
    callbacks: Arc<Mutex<HashMap<CallbackId, Box<dyn CallbackHandler>>>>,
    next_id: Arc<Mutex<CallbackId>>,
}

impl Default for CallbackRegistry {
    fn default() -> Self {
        Self {
            callbacks: Arc::new(Mutex::new(HashMap::new())),
            next_id: Arc::new(Mutex::new(1)), // 从1开始，0作为无效ID
        }
    }
}

impl CallbackRegistry {
    // 创建新的回调注册表
    pub fn new() -> Self {
        Self::default()
    }
    
    // 注册回调函数
    pub fn register(&self, handler: Box<dyn CallbackHandler>) -> Result<CallbackId, CallbackError> {
        let mut next_id = self.next_id.lock().map_err(|_| CallbackError::RegistrationFailed)?;
        let id = *next_id;
        
        // 增加下一个ID
        *next_id += 1;
        
        // 存储回调
        let mut callbacks = self.callbacks.lock().map_err(|_| CallbackError::RegistrationFailed)?;
        callbacks.insert(id, handler);
        
        Ok(id)
    }
    
    // 注销回调函数
    pub fn unregister(&self, id: CallbackId) -> Result<bool, CallbackError> {
        if id == 0 {
            return Err(CallbackError::InvalidCallbackId);
        }
        
        let mut callbacks = self.callbacks.lock().map_err(|_| CallbackError::ExecutionFailed)?;
        
        if callbacks.remove(&id).is_some() {
            Ok(true)
        } else {
            Err(CallbackError::CallbackNotFound)
        }
    }
    
    // 执行回调函数
    pub fn execute(&self, id: CallbackId, args: Box<dyn Any>) -> Result<Box<dyn Any>, CallbackError> {
        if id == 0 {
            return Err(CallbackError::InvalidCallbackId);
        }
        
        let callbacks = self.callbacks.lock().map_err(|_| CallbackError::ExecutionFailed)?;
        
        if let Some(handler) = callbacks.get(&id) {
            Ok(handler.call(args))
        } else {
            Err(CallbackError::CallbackNotFound)
        }
    }
    
    // 获取回调数量
    pub fn count(&self) -> Result<usize, CallbackError> {
        let callbacks = self.callbacks.lock().map_err(|_| CallbackError::ExecutionFailed)?;
        Ok(callbacks.len())
    }
}